package com.zjdiepu.www.manage.api.his;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SortFieldType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.mapper.his.HisYwBusinessBuyerVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessBuyerVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.his.IHisYwBusinessBuyerService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessBuyerService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.his.dto.HisYwBusinessBuyer;
import com.zjdiepu.www.model.his.ext.HisYwBusinessBuyerExt;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.ext.YwBusinessBuyerExt;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.model.yw.response.YwBusinessInfoResponse;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.util.YwExtHelper;

/**
 * 购车人信息历史记录Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年09月21日 14时40分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "HisYwBusinessBuyerController", produces="application/json;charset=UTF-8")
@Api(tags = {"购车人信息历史记录"}, produces="application/json;charset=UTF-8")
public class HisYwBusinessBuyerController extends BaseController {
    @Resource
    private IHisYwBusinessBuyerService hisYwBusinessBuyerService;
    @Resource
    private IYwBusinessBuyerService ywBusinessBuyerService;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    @Resource
    private YwBusinessBuyerVoMapper ywBusinessBuyerVoMapper;
    @Resource
    private HisYwBusinessBuyerVoMapper hisYwBusinessBuyerVoMapper;
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
	@ApiOperation(value = "主键查询多表业务信息", response = YwBusiness.class, httpMethod="POST", tags={"主键查询多表"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getMultiById", method = RequestMethod.POST)
	public ApiResponse getMultiById(String id) {
		getCurrentUser();
		if (StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		YwBusinessDetail ywBusinessDetail = ywBusinessService.getMultiById(id);
		if (null == ywBusinessDetail) {
			ExceptionHelper.thow(ResultFlagType.MISSING);
		}
		YwBusinessInfoResponse response = new YwBusinessInfoResponse();
		response.setYwBusinessDetail(ywBusinessDetail);
		// 查询购车人信息
		YwBusinessBuyerExt ywBusinessBuyerExt = new YwBusinessBuyerExt();
		ywBusinessBuyerExt.setBaseWhere();
		ywBusinessBuyerExt.withOutPage();
		ywBusinessBuyerExt.setBusiId(id);
		List<YwBusinessBuyer> ywBusinessBuyers = ywBusinessBuyerService.selectByExt(ywBusinessBuyerExt);
		for (YwBusinessBuyer ywBusinessBuyer : ywBusinessBuyers) {
			ywBusinessBuyerVoMapper.mapper(ywBusinessBuyer);
			String carManType = ywBusinessBuyer.getCarManType();
			SimpleDataDictionary cachedDataDic = cachedDictionaryService.getCachedDataDic(carManType, DataDicType.CREDIT_PEOPLE_TYPE);
			if (null != cachedDataDic) {
				response.addYwBusinessBuyer(cachedDataDic.getValue(), ywBusinessBuyer);
			}
		}
		return ApiResponse.success(response);
	}

    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 修改购车人 <br/>
     * @param ywBusinessExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改购车人/购车人历史",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "multiList", method = RequestMethod.POST)
    public ApiResponse multiList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        Boolean buyerHis = ywBusinessQueryRequest.getBuyerHis();
        if(null != buyerHis && buyerHis) { //购车人历史修改列表
        	Date buyerHisTimeStartDate = ywBusinessQueryRequest.getBuyerHisTimeStartDate();
        	if(buyerHisTimeStartDate != null) {
        		ywBusinessQueryRequest.setBuyerHisTimeStart(DateUtil.truncAndAddDays(buyerHisTimeStartDate, 0).getTime() / 1000);
        	} 
        	Date buyerHisTimeEndDate = ywBusinessQueryRequest.getBuyerHisTimeEndDate();
        	if(buyerHisTimeEndDate != null){
        		ywBusinessQueryRequest.setBuyerHisTimeEnd(DateUtil.truncAndAddDays(buyerHisTimeEndDate, 1).getTime() / 1000);
        	}
        } else { //修改购车人列表
        	YwExtHelper.initExt(ywBusinessQueryRequest, SortFieldType.SUBMIT_TIME);
//    		列表数据范围：初审一审中（包括）到 提交终审中（包括）
        	ywBusinessQueryRequest.setMinBusiStatus(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_ZHONG.getCode()); //初审一审中（包括）
        	ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.QIAN_SHU_HE_TONG_ZHONG.getCode()); //提交终审中（包括）
        }
        
    	int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
    	page.setRecords(records);
    	if (records > 0) {
    		List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
    		ywBusinessVoMapper.mapper(ywBusinesss);
    		page.setRows(ywBusinesss);
    	} else {
    		page.setRows(CollectionInitUtil.emptyList());
    	}
    	return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增购车人信息历史记录 <br/>
     * @param hisYwBusinessBuyer
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增购车人信息历史记录", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute HisYwBusinessBuyer hisYwBusinessBuyer) {
    	AbstractSysUser currentUser = getCurrentUser();
    	hisYwBusinessBuyer.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	hisYwBusinessBuyer.setModifierName(currentUser.getName());
        hisYwBusinessBuyerService.saveUpdateAndDelete(hisYwBusinessBuyer, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除购车人信息历史记录<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除购车人信息历史记录", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	hisYwBusinessBuyerService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用购车人信息历史记录<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用购车人信息历史记录", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	hisYwBusinessBuyerService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用购车人信息历史记录<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用购车人信息历史记录", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	hisYwBusinessBuyerService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改购车人信息历史记录 <br/>
     * @param hisYwBusinessBuyer
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改购车人信息历史记录", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute HisYwBusinessBuyer hisYwBusinessBuyer) {
    	AbstractSysUser currentUser = getCurrentUser();
    	hisYwBusinessBuyer.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	hisYwBusinessBuyer.setModifierName(currentUser.getName());
    	hisYwBusinessBuyerService.saveUpdateAndDelete(hisYwBusinessBuyer, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询购车人信息历史记录<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询购车人信息历史记录", response = HisYwBusinessBuyer.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       HisYwBusinessBuyer hisYwBusinessBuyer = hisYwBusinessBuyerService.selectById(id);
       if(null == hisYwBusinessBuyer) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(hisYwBusinessBuyer);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询购车人信息历史记录 <br/>
     * @param hisYwBusinessBuyerExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询购车人信息历史记录",response = HisYwBusinessBuyer.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute HisYwBusinessBuyerExt hisYwBusinessBuyerExt){
        hisYwBusinessBuyerExt.notDeleted();
        PageVo page = getPage(hisYwBusinessBuyerExt);
        int records = hisYwBusinessBuyerService.countByExt(hisYwBusinessBuyerExt);
        page.setRecords(records);
        if (records > 0) {
            List<HisYwBusinessBuyer> hisYwBusinessBuyers = hisYwBusinessBuyerService.selectByExt(hisYwBusinessBuyerExt);
            page.setRows(hisYwBusinessBuyers);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
